package com.feng.zshop.backend.controller;

import com.feng.zshop.backend.dto.ProductDTO;
import com.feng.zshop.backend.service.ProductService;
import com.feng.zshop.backend.service.ProductTypeService;
import com.feng.zshop.backend.vo.ProductVO;
import com.feng.zshop.common.constant.PaginationConstant;
import com.feng.zshop.common.utils.ResponseResult;
import com.feng.zshop.model.Product;
import com.feng.zshop.model.ProductType;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Lee
 * @date 2019/2/17
 */
@Controller
@RequestMapping("/backend/product")
public class ProductController {

    private final static Logger LOGGER = LoggerFactory.getLogger(ProductController.class);

    @Autowired
    private ProductTypeService productTypeService;

    @Autowired
    private ProductService productService;

    @ModelAttribute(value = "productTypes")
    public List<ProductType> loadProductTypes(@RequestParam(value = "id",required = false)Integer id, Model model, HttpServletRequest request){
        if (id != null && request.getRequestURI().contains("/modify")){
            Product product = productService.getProductById(id);
            ProductVO productVO = new ProductVO();
            BeanUtils.copyProperties(product, productVO);
            model.addAttribute("productVO", productVO);
        }
        return productTypeService.findProductTypeEnable();
    }

    @RequestMapping("/findAll")
    public String findAllProduct(@RequestParam(value = "pageNum",required = false)Integer pageNum, Model model){
        if (ObjectUtils.isEmpty(pageNum)){
            pageNum = PaginationConstant.PAGE_NUMBER;
        }
        Page<Object> page = PageHelper.startPage(pageNum, PaginationConstant.PAGE_SIZE);
        List<Product> products = productService.findAll();
        PageInfo<Product> pageInfo = new PageInfo<>(products);
        model.addAttribute("pageInfo", pageInfo);
        return "productManager";
    }

    @PostMapping("/add")
    public String addProduct(@Valid ProductVO productVO,@RequestParam(value = "pageNum") Integer pageNum, HttpSession session, Model model){
        String uploadPath = session.getServletContext().getRealPath("/WEB-INF/upload");

        try {
            ProductDTO productDTO = new ProductDTO();
            BeanUtils.copyProperties(productVO, productDTO);

            productDTO.setInputStream(productVO.getFile().getInputStream());
            productDTO.setFileName(productVO.getFile().getOriginalFilename());
            productDTO.setUploadPath(uploadPath);
            productService.saveProduct(productDTO);

            model.addAttribute("successMsg", "添加成功");
        } catch (Exception e) {
            model.addAttribute("errorMsg", e.getMessage());
        }
        return "forward:findAll?pageNum=" + pageNum;
    }

    @PostMapping("/checkName")
    @ResponseBody
    public Map<String, Object> checkName(@RequestParam(value = "name",required = true) String name){
        Map<String, Object> resMap = new HashMap<>();
        boolean valid = productService.checkName(name);
        if (valid) {
            resMap.put("valid",true);
        }else {
            resMap.put("valid",false);
            resMap.put("message","商品名称 " + name + " 已经存在");
        }
        return resMap;
    }

    @GetMapping("/removeById")
    @ResponseBody
    public ResponseResult removeById(@RequestParam(value = "id", required = true) Integer id){
        productService.deleteProductById(id);
        return ResponseResult.successNoData("删除商品成功");
    }

    @GetMapping("/findById")
    @ResponseBody
    public ResponseResult findById(@RequestParam(value = "id",required = true) Integer id){
        return ResponseResult.successNoMessage(productService.getProductById(id));
    }

    @PostMapping("/modify")
    public String modify(@Valid ProductVO productVO, @RequestParam(value = "pageNum") Integer pageNum, HttpSession session, Model model){
        String uploadPath = session.getServletContext().getRealPath("/WEB-INF/upload");

        try {
            ProductDTO productDTO = new ProductDTO();
            BeanUtils.copyProperties(productVO, productDTO);

            productDTO.setInputStream(productVO.getFile().getInputStream());
            productDTO.setFileName(productVO.getFile().getOriginalFilename());
            productDTO.setUploadPath(uploadPath);
            productService.updateProduct(productDTO);

            model.addAttribute("successMsg", "修改成功");
        } catch (Exception e) {
            model.addAttribute("errorMsg", e.getMessage());
        }
        return "forward:findAll?pageNum=" + pageNum;
    }

    @GetMapping("/getImage")
    public void getImage(@RequestParam(value = "path", required = true) String path, OutputStream outputStream) throws IOException {
        try {
            FileUtils.copyFile(new File(path),outputStream);
        } catch (IOException e) {
            throw new IOException("获取图片失败");
        }
    }

}
